var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session')
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var adminRouter = require('./routes/admin');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/vxe-table', express.static('node_modules/vxe-table'))
app.use('/xe-utils', express.static('node_modules/xe-utils'))
app.use("/xe-ajax", express.static('node_modules/xe-ajax'))
app.use("/moment", express.static('node_modules/moment'))
app.use(express.static(path.join(__dirname, 'public')));

// 使用session
app.use(cookieSession({
  keys: ['liuzp'], // 密钥
  maxAge: 1000 * 60 * 60  //有效期
}))
// session延时
app.use((req, res, next) => {
  req.session.nowInMinutes = Math.floor(Date.now() / 60e3)  // 每分钟更新一次
  next()
})

/* 文件上传 */
app.use('/multer',require("./middleware/multer"));

/* 用户路由 */
app.use('/', indexRouter);

/* 管理员路由 */
app.use('/admin', adminRouter);

/* 用户管理 */
app.use('/user', usersRouter);

/* 标签管理 */
app.use('/label', require('./routes/labels'))

/* 轮播图 */
app.use('/shuff', require('./routes/shuff'));

/* 相册 */
app.use('/photo', require('./routes/photo'));

/* 博客 */
app.use('/blog',require('./routes/blogEdit'));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
